#-*- coding:utf-8 -*-
from gevent import monkey
monkey.patch_all()
from flask import Flask, request, render_template
from gevent import pywsgi
import argparse
import os
from requests import post
import json
from execute import execute_text
def set_args():
    """设置所需参数"""
    parser = argparse.ArgumentParser()
    '''parser.add_argument('--device', default='0', type=str, help='设置预测时使用的显卡,使用CPU设置成-1即可')
    parser.add_argument('--output_dir', default='output_dir/checkpoint-111844', type=str, help='模型文件路径')
    parser.add_argument('--vocab_path', default='vocab/vocab.txt', type=str, help='词表，该词表为小词表，并增加了一些新的标记')
    parser.add_argument('--batch_size', default=3, type=int, help='生成标题的个数')
    parser.add_argument('--generate_max_len', default=32, type=int, help='生成标题的最大长度')
    parser.add_argument('--repetition_penalty', default=1.2, type=float, help='重复处罚率')
    parser.add_argument('--top_k', default=5, type=float, help='解码时保留概率最高的多少个标记')
    parser.add_argument('--top_p', default=0.95, type=float, help='解码时保留概率累加大于多少的标记')
    parser.add_argument('--max_len', type=int, default=512, help='输入模型的最大长度，要比config中n_ctx小')'''
    parser.add_argument('--http_id', type=str, default="0.0.0.0", help='ip地址')
    parser.add_argument('--port', type=int, default=5555, help='端口号')
    return parser.parse_args()


def return_img_stream(img_local_path):
    import base64
    img_stream = ''
    with open(img_local_path,encoding='unicode_escape', mode='r') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream)
    return img_stream

def start_sever():
    args = set_args()
    '''os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICE"] = args.device
    device = torch.device("cuda" if torch.cuda.is_available() and int(args.device) >= 0 else "cpu")
    # 实例化tokenizer和model
    tokenizer = BertTokenizer.from_pretrained(args.vocab_path, do_lower_case=True)
    model = GPT2LMHeadModel.from_pretrained(args.output_dir)
    model.to(device)
    model.eval()
    print("load model ending!")'''
    app = Flask(__name__)
    #app = Flask(__name__,  static_folder='', static_url_path='')

    @app.route('/')
    def initial():
        return render_template("initial.html")

    @app.route('/demo', methods=['Get', 'POST'])
    def demo_response_request():
        if request.method == 'POST':
            content = request.form.get('content')

            url = "http://192.168.43.75:5555/news-title-generate"
            data = {'content': content}

            r = post(url, data=data)
            txt=r.text
            begin=txt.find('生成的第1个标题为')
            end=txt.find('      </textarea>\n    </form>')
            print(begin)
            print(end)
            titles=""
            if(begin!=-1 and end!=-1):
                #print(txt[begin:end])
                titles=txt[begin:end]

            '''titles = ['第一个假标题','第二个假标题','第三个假标题']
            title_str = ""
            for i, t in enumerate(titles):
                title_str += "生成的第{}个标题为：{}\n".format(i+1, t)'''
            execute_text(content)
            print("after")
            src1 = 'static/0.jpg'
            src2 = 'static/1.jpg'
            src3 = 'static/2.jpg'
            src4 = 'static/3.jpg'
            first=" "
            second=" "
            
            # with open("static/sentences.txt", "r") as f:
            sentences = " "
            return render_template("demo_generate.html", content=content, first=first,second=second,sentences=sentences,titles=titles,src1=src1,src2=src2,src3=src3,src4=src4)
        return render_template("demo_index.html")

    '''@app.route('/graph-generate',methods=['Get','POST'])
    def graph_response_request():
        if request.method=='POST':
            content = request.form.get('content')
            src1='static/01.jpg'
            src2='static/02.jpg'
            #graph=return_img_stream(img_local_path)
            return render_template("graph_generate.html",content=content,src1=src1,src2=src2)
        return render_template("graph_index.html")

    @app.route('/push-generate',methods=['Get','POST'])
    def push_response_request():
        if request.method == 'POST':
            content = request.form.get('content')
            titles = ['第一个假标题', '第二个假标题', '第三个假标题']
            title_str = ""
            for i, t in enumerate(titles):
                title_str += "生成的第{}个标题为：{}\n".format(i + 1, t)
            return render_template("demo_generate.html", content=content, titles=title_str)
        return render_template("demo_index.html")'''

    server = pywsgi.WSGIServer((str(args.http_id), args.port), app)
    server.serve_forever()


if __name__ == '__main__':
    start_sever()